/*
 * main.cpp
 *
 *  Created on: 3 oct. 2009
 *      Author: Maxime Gaudin
 */

#ifndef VECTOR_H
	#include <vector>
	#define VECTOR_H
#endif

#ifndef STREAM_H
	#include <iostream>
	#include <fstream>
	#define STREAM_H
#endif

#include "WordStream.h"

using namespace std;

int IsWordMatch(string Word, string Letters)
{
	for(unsigned int i = 0; i < Letters.length(); i++)
	{
		for(unsigned int j = 0; j < Word.length(); j++)
		{
			if(Letters[i] == Word[j])
			{
				Letters.erase(Letters.begin() + i--);
				Word.erase(Word.begin() + j--);
			}
		}
	}

	if(Word.length() == 0) return 1;
	return 0;
}

vector<string> GetMatchingWords(WordStream::WordStream WS, string Letters)
{
	vector<string> MatchingWords;
	WS.SeekToStart();

	while(!WS.IsEndOfStream())
	{
		string tmpWord = WS.GetNextWord();
		if(IsWordMatch(tmpWord, Letters)) MatchingWords.push_back(tmpWord);
	}

	return MatchingWords;
}

string GetLongestWord(vector<string> MatchingWords)
{
	unsigned int MaxIndex = 0;
	unsigned int MaxSize = MatchingWords[0].length();

	for(unsigned int i = 1; i < MatchingWords.size(); i++)
	{
		if(MatchingWords[i].length() > MaxSize)
		{
			MaxIndex = i;
			MaxSize = MatchingWords[i].length();
		}
	}

	return MatchingWords[MaxIndex];
}

int main(int argc, char** argv)
{
	cout << "*******************************************" << endl;
	cout << "************** DES LETTRES ****************" << endl;
	cout << "************* Maxime Gaudin ***************" << endl;
	cout << "*******************************************" << endl;
	cout << "Chargement de la liste de mots..." << endl;
	WordStream::WordStream WS("/tmp/WordList.txt");
	cout << "Liste chargée !" << endl;

	cout << endl;
	cout << endl;

	while(true)
	{
		string Letters;
		cout << "Lettres : ";
		cin >> Letters;

		string Result = GetLongestWord(GetMatchingWords(WS, Letters));
		cout << "Résultat : " << Result << " (" << Result.length() << " caractères )" << endl;
		cout << endl;
	}
}
